<script lang="ts" setup>
import type { VxeGridListeners, VxeTableGridOptions } from '#/adapter/vxe-table'

import { onMounted, onUnmounted, ref, watch } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import {Button, Dropdown, Input, Menu, MenuItem, message, Space, Switch} from 'ant-design-vue'

import fileManage from '#/adapter/component/FileManage/index.vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import {factoryExcel, factorylList, saveFactory} from '#/api/factory'
import {editSupply, getContractList} from '#/api/supply'
import exportList from '#/views/backend/supply/modules/exportList.vue'

import popupForm from './modules/popupForm.vue'

const searchValue = ref()
/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}

const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'SupplyCode',
      label: '编号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'SupplyNa',
      label: '供应商名称',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'SupplyName',
      label: '公司名称',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'production_mode',
      label: '生产模式',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'production_level',
      label: '生产级别',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'sg_month_capacity',
      label: '索歌月产能',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'station',
      label: '车位',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'tail_personnel',
      label: '尾部人员数',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'cooperate_mode',
      label: '合作方式',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplyman1',
      label: '联系姓名',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplytel1',
      label: '手机号码',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplyadd',
      label: '地址',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'roleCategoryId_RoleCategory',
      label: '权限分类',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '未上传',
            value: 0,
          },
          {
            label: '已上传',
            value: 1,
          },
        ],
        showSearch: true,
      },
      label: '是否上传附件',
      fieldName: 'isUploadFile',
      operator: 'false',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Remark',
      label: '备注',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'erp_id',
      label: 'ERPID',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplyid',
      label: '康雷ID',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Operator',
      label: '创建人',
      operator: 'LIKE',
    },

    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'InputDate',
      label: '创建时间',
      operator: 'RANGE',
    },
    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'sync_time',
      label: '同步时间',
      operator: 'RANGE',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
    trigger: 'row',
  },
  cellConfig: {},
  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    {
      field: 'SupplyCode',
      title: '供应商编码',
      width: 150,
    },
    {
      title: '供应商简称',
      field: 'SupplyNa',
      width: 200,
    },
    { field: 'SupplyName', title: '公司名称', width: 200 },
    {
      field: 'Supplytype',
      title: '供应商类型',
      width: 80,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '成品',
            value: 2,
          },
          { color: 'warning', label: '物料', value: 1 },
        ],
      },
    },
    {
      title: '生产模式',
      field: 'production_mode',
      width: 150,
    },
    {
      title: '生产级别',
      field: 'production_level',
      width: 100,
    },
    {
      title: '索歌月产能',
      field: 'month_capacity',
      width: 120,
    },
    {
      title: '车位',
      field: 'station',
      width: 80,
    },
    {
      title: '尾部人员数',
      field: 'tail_personnel',
      width: 100,
    },
    {
      title: '合作方式',
      field: 'cooperate_mode',
      width: 120,
    },
    {
      field: 'Supplyman1',
      title: '联系人',
      width: 100,
    },
    {
      title: '手机号码',
      field: 'Supplytel1',
      width: 120,
    },
    {
      title: '地址',
      field: 'Supplyadd',
      width: 200,
    },
    {
      title: '权限分类',
      field: 'roleCategoryId.RoleCategory',
      width: 120,
    },
    {
      title: '备注',
      field: 'Remark',
      width: 200,
    },
    {
      title: '是否上传附件',
      field: 'isUploadFile',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已上传',
            value: 1,
          },
          { color: 'error', label: '未上传', value: 0 },
        ],
      },
    },
    {
      title: '停用',
      field: 'Shutout',
      width: 100,
      slots: { default: 'Shutout' },
    },

    {
      title: 'ERPID',
      field: 'erp_id',
      width: 100,

    },
    {
      title: '创建人',
      field: 'Operator',
      width: 150,
    },

    {
      title: '创建时间',
      field: 'InputDate',
      width: 150,
    },

    {
      title: '同步时间',
      field: 'sync_time',
      width: 150,
    },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 80,
      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const search: any[] = []
        for (const [key, value] of Object.entries(formValues)) {
          if (value === null || value === '' || value === undefined) continue
          const fieldSchema = formOptions.schema.find((i: any) => i.fieldName === key)
          // 处理特殊字段格式
          let fieldValue = value

          search.push({
            field: key,
            val: fieldValue,
            operator: fieldSchema?.operator,
            render: fieldSchema?.render,
          })
        }
        searchValue.value = search
        const res = await factorylList({
          page: page.currentPage,
          limit: page.pageSize,
          quick_search:quick_search.value,
          search,
        })

        res.list.forEach((row) => {
          row.Shutout = row.Shutout === 1
        })
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },

  id: 'supply_list',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
  rowClassName({ row }) {
    return row.Posted === 0 ? 'text-red-500' : ''
  },
}

// 双击打开编辑
const gridEvents: VxeGridListeners = {
  cellDblclick: ({ row }) => {
    openEdit(row, 'edit')
  },
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
})

//  按钮的禁用状态
const isDisabled = ref(true)

function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      isDisabled.value = !selectedRecords || selectedRecords.length === 0
    } else {
      isDisabled.value = true
    }
  } catch {
    isDisabled.value = true
  }
}

// 使用watch监听gridApi的变化
watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)
function modelClose() {
  gridApi.reload()
}

const [formModal, formModalApi] = useVbenModal({
  connectedComponent: popupForm,
})
// 编辑
function openEdit(res: any, but: any) {
  formModalApi.setData({ rowData: res.id, view: but }).open()
}

function openEdits() {
  const selectedRecords = gridApi.grid.getCheckboxRecords()
  if (selectedRecords.length === 0) {
     message.error("请选择数据")
    return
  }
  const data = selectedRecords.map((record: any) => record.id)
  formModalApi.setData({ rowData: data, view: 'edit' }).open()
}

function openContractModalApi() {
  const parmas = {
    search: searchValue.value,
    quick_search:quick_search.value,
  }
  factoryExcel(parmas).then((res: any) => {
    if (res.data.code === 1) {
      window.open(res.data.data.path)
      message.success(res.data.data.msg)
    } else {
      message.error(res.data.data.msg)
    }
  })
}

// 合同管理
const [fileManageModal, fileManageModalApi] = useVbenModal({
  connectedComponent: fileManage,
})

function openFileModal() {
  const data = gridApi.grid.getCheckboxRecords()
  const ids = data.map((item: any) => item.id)
  fileManageModalApi.setData({ data: ids, type: '4', search: searchValue.value }).open()
}
const [exportModal, exportModalApi] = useVbenModal({
  connectedComponent: exportList,
})

function exportContractModule(data: any) {
  const row = gridApi.grid.getCheckboxRecords()
  exportModalApi.setData({ data: row.map((item: any) => item.id), contract_type: data.key }).open()
}
const contractList = ref({})
onMounted(() => {
  getContractList().then((res: any) => {
    contractList.value = res || {}
  })
})

function changeShutout(data: any, row: any) {
  saveFactory({ id: row.id, Shutout: data ? 1 : 0 }).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.success(res.data.msg)
    }
  })
}

</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="openEdit('', 'add')">新建</Button>
            <Button type="primary" @click="openEdits">编辑</Button>
            <Button type="primary" @click="openContractModalApi"> 导出 </Button>
            <Button type="primary" class="my-green-btn" @click="openFileModal()">附件管理与导出</Button>
            <Dropdown>
              <Button type="primary" v-if="!isDisabled">导出框架合同</Button>
              <template #overlay>
                <Menu @click="exportContractModule">
                  <MenuItem v-for="(value, key) in contractList" :key="key">
                    {{ value }}
                  </MenuItem>
                </Menu>
              </template>
            </Dropdown>
          </Space>
        </div>
      </template>
      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="通过ID模糊搜索" style="width: 200px; margin-right: 8px" @change="doSearch" />
      </template>
      <!-- 操作列插槽 -->
      <template #SupplyNa="{ row }">
        <div>简称: {{ row.SupplyNaStr }}</div>
        <div>全称： {{ row.SupplyName }}</div>
      </template>
      <template #Shutout="{ row }">
        <Switch v-model:checked="row.Shutout"  @change="(val) => changeShutout(val, row)" />
      </template>

      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <Space>
          <Button type="primary" size="small" @click="openEdit(row, 'edit')"> 编辑 </Button>
        </Space>
      </template>
    </Grid>
    <formModal @refresh="modelClose()" />
    <fileManageModal @close="modelClose()" />
    <exportModal @refresh="modelClose()" />
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
